package top.chenfu.boot.auth.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.chenfu.boot.auth.service.UserServiceImpl;
import top.chenfu.boot.auth.vo.UserVo;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping(value = "login")
public class LoginController {

    @Autowired
    private UserServiceImpl userService;

    @ApiOperation(value = "用户登录接口", notes = "用户登录方法")
    @PostMapping
    public ResponseEntity login(@RequestBody @Validated @ApiParam(name = "登录参数", value = "JSON格式", required = true) UserVo userVo, BindingResult result, HttpSession session) {
        if (result.hasErrors()) {
            userVo.setCode(HttpStatus.BAD_REQUEST.value());
            userVo.setMsg(result.getAllErrors().get(0).getDefaultMessage());
            return new ResponseEntity<>(userVo, HttpStatus.BAD_REQUEST);
        }
        String token = userService.login(userVo, session);
//      说明用户名或密码不正确
        if (StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(token, HttpStatus.OK);
    }

}
